package com.zhangtai.modules.controller.admin;

import com.alibaba.fastjson.JSONObject;
import com.zhangtai.common.annotation.SysAuthorityLog;
import com.zhangtai.exception.QwMsg;
import com.zhangtai.modules.constVo.NoticeConst;
import com.zhangtai.modules.controller.aouthLogin.LoginController;
import com.zhangtai.modules.dto.RegularDto;
import com.zhangtai.modules.entity.employee.EmployeeBpmEntity;
import com.zhangtai.modules.entity.employee.EmployeeInfoEntity;
import com.zhangtai.modules.entity.employee.EmployeeRecruitmentEntity;
import com.zhangtai.modules.entity.regular.RegularBpmEntity;
import com.zhangtai.modules.service.baseFromMssql.BaseMssqlServiceImpl;
import com.zhangtai.modules.service.employee.EmployeeBpmService;
import com.zhangtai.modules.service.employee.EmployeeInfoService;
import com.zhangtai.modules.service.employee.EmployeeRecruitmentService;
import com.zhangtai.modules.service.regular.RegularBpmService;
import com.zhangtai.modules.vo.RegularDayVo;
import com.zhangtai.modules.vo.RegularListVo;
import com.zhangtai.modules.vo.RegularVo;
import com.zhangtai.modules.vo.UpdateRegularVo;
import com.zhangtai.utils.*;
import io.netty.util.internal.StringUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("regular")
@Api(tags="新员工转正接口")
@Slf4j
public class RegularController {
    @Autowired
    private EmployeeInfoService employeeInfoService;
    @Autowired
    private BaseMssqlServiceImpl baseMssqlService;
    @Autowired
    private LoginController loginController;
    @Autowired
    private JobController jobController;
    @Autowired
    private RegularBpmService regularBpmService;
    @Autowired
    private EmployeeBpmService employeeBpmService;
    @Autowired
    private QwMsg qwMsg;
    @Autowired
    private EmployeeRecruitmentService employeeRecruitmentService;

/*    @PostMapping("/list")
    @ApiOperation(value="分页查询转正信息")
    @PreAuthorize("hasAuthority('emp:ygzz:get')")
    public R<PageResult<RegularDto>> getRegularList(@RequestBody RegularVo regularVo, HttpServletRequest request) throws Exception{

        List<Long>  jobSystemIds = new ArrayList<>();
        List<Long>  jlineSystemIds = new ArrayList<>();
        //获取当前用户角色下公司Id
        R checkR = loginController.checkOrgPermission(request,null,false);
        if(!R.isOk.equals(checkR.getStatus())){
            return checkR;
        }
        List<Long> orgIds = (List<Long>) checkR.getData();
//        log.info("公司组orgIds：{}",orgIds);
        //体系
        if(!StringUtil.isNullOrEmpty(regularVo.getJobSystem())){
            jobSystemIds = baseMssqlService.findSystemIdByName(regularVo.getJobSystem());
        }
        //体系
        if(!StringUtil.isNullOrEmpty(regularVo.getLineSystem())){
            jlineSystemIds = baseMssqlService.findLineIdByName(regularVo.getLineSystem());
        }
        List<Long> org = null;
        List<Long> unit = null;
        List<Long> job = null;
        if(!ObjectUtils.isEmpty(regularVo.getOrgname())){
            org = baseMssqlService.finOrgByOrgName(regularVo.getOrgname());
        }
        if(!ObjectUtils.isEmpty(regularVo.getUnitname())){
            unit = baseMssqlService.finOrgByOrgName(regularVo.getUnitname());
        }

        if(!ObjectUtils.isEmpty(regularVo.getJobname())){
            job = baseMssqlService.findJobIdByJobName(regularVo.getJobname());
        }
        JSONObject  userInfo = loginController.getUserInfo(request).getData();
        String code = userInfo.getString("usercode");
        regularVo.setCode(code);
        PageResult<EmployeeInfoEntity> pageResult= employeeInfoService.getRegularList(regularVo,jobSystemIds,jlineSystemIds,orgIds,org,unit,job);
        List<EmployeeInfoEntity> resultList = pageResult.getList();
        ArrayList<RegularDto> dtos = new ArrayList<>();
        for (EmployeeInfoEntity employeeInfoEntity : resultList) {
            RegularDto regularDto = BeanUtilsMabach.doToDto(employeeInfoEntity, RegularDto.class);
            Long jobId = regularDto.getJobId();
            String jobName = jobController.getJobName(jobId);
            regularDto.setJobname(jobName); //岗位名称
            Long jobLevelId = regularDto.getJobLevelId();
            String jobLevelNameById = jobController.getJobLevelNameById(jobLevelId);
            regularDto.setJobLevel(jobLevelNameById); //职级
            Long orgId = regularDto.getOrgId();
            String orgNameById = jobController.getOrgNameById(orgId);
            regularDto.setOrgname(orgNameById); //公司
            Long unitId = regularDto.getUnitId();
            String unitName = jobController.getOrgNameById(unitId);
            regularDto.setUnitname(unitName); //部门
            Date regularDay = employeeInfoEntity.getRegularDay();
            Integer probationday = employeeInfoEntity.getProbationday();
            Date hiredate = employeeInfoEntity.getHiredate();
            if (ObjectUtils.isEmpty(regularDay)){
                if(!ObjectUtils.isEmpty(probationday)){
                    regularDay = DateUtils.addDateMonths(hiredate, probationday);
                    regularDto.setRegularDay(regularDay); //预计转正日期
                }
            }
            dtos.add(regularDto);

        }


        PageResult<RegularDto> regularDtoPageResult = new PageResult<>();
        regularDtoPageResult.setList(dtos);
        regularDtoPageResult.setTotalCount(pageResult.getTotalCount());
        regularDtoPageResult.setCurrPage(pageResult.getCurrPage());
        regularDtoPageResult.setPageSize(pageResult.getPageSize());
        regularDtoPageResult.setTotalPage(pageResult.getTotalPage());

        return R.ok(regularDtoPageResult);

    }*/


    @PostMapping("/list")
    @ApiOperation(value="分页查询转正信息")
    @PreAuthorize("hasAuthority('emp:ygzz:get')")
    public R<PageResult<RegularDto>> getRegularList(@RequestBody RegularVo regularVo, HttpServletRequest request) throws Exception{

        List<Long>  jobSystemIds = new ArrayList<>();
        List<Long>  jlineSystemIds = new ArrayList<>();
        //获取当前用户角色下公司Id
        R checkR = loginController.checkOrgPermission(request,null,false);
        if(!R.isOk.equals(checkR.getStatus())){
            return checkR;
        }
        List<Long> orgIds = (List<Long>) checkR.getData();
//        log.info("公司组orgIds：{}",orgIds);
        //体系
        if(!StringUtil.isNullOrEmpty(regularVo.getJobSystem())){
            jobSystemIds = baseMssqlService.findSystemIdByName(regularVo.getJobSystem());
        }
        //体系
        if(!StringUtil.isNullOrEmpty(regularVo.getLineSystem())){
            jlineSystemIds = baseMssqlService.findLineIdByName(regularVo.getLineSystem());
        }
        List<Long> org = null;
        List<Long> unit = null;
        List<Long> job = null;
        if(!ObjectUtils.isEmpty(regularVo.getOrgname())){
            org = baseMssqlService.finOrgByOrgName(regularVo.getOrgname());
        }
        if(!ObjectUtils.isEmpty(regularVo.getUnitname())){
            unit = baseMssqlService.finOrgByOrgName(regularVo.getUnitname());
        }

        if(!ObjectUtils.isEmpty(regularVo.getJobname())){
            job = baseMssqlService.findJobIdByJobName(regularVo.getJobname());
        }
        JSONObject  userInfo = loginController.getUserInfo(request).getData();
        String code = userInfo.getString("usercode");
        regularVo.setCode(code);
        PageResult<EmployeeRecruitmentEntity> pageResult= employeeRecruitmentService.getRegularListPage(regularVo,jobSystemIds,jlineSystemIds,orgIds,org,unit,job);
        List<EmployeeRecruitmentEntity> resultList = pageResult.getList();
        ArrayList<RegularDto> dtos = new ArrayList<>();
        for (EmployeeRecruitmentEntity employeeRecruitmentEntity : resultList) {
            RegularDto regularDto = BeanUtilsMabach.doToDto(employeeRecruitmentEntity, RegularDto.class);
            Long jobId = regularDto.getJobId();
            String jobName = jobController.getJobName(jobId);
            regularDto.setJobname(jobName); //岗位名称
            Long jobLevelId = regularDto.getJobLevelId();
            String jobLevelNameById = jobController.getJobLevelNameById(jobLevelId);
            regularDto.setJobLevel(jobLevelNameById); //职级
            Long orgId = regularDto.getOrgId();
            String orgNameById = jobController.getOrgNameById(orgId);
            regularDto.setOrgname(orgNameById); //公司
            Long unitId = regularDto.getUnitId();
            String unitName = jobController.getOrgNameById(unitId);
            regularDto.setUnitname(unitName); //部门
            Date regularDay = employeeRecruitmentEntity.getRegularDay();
            Integer probationday = employeeRecruitmentEntity.getProbationday();
            Date hiredate = employeeRecruitmentEntity.getHiredate();
            if (ObjectUtils.isEmpty(regularDay)){
                if(!ObjectUtils.isEmpty(probationday)){
                    regularDay = DateUtils.addDateMonths(hiredate, probationday);
                    regularDto.setRegularDay(regularDay); //预计转正日期
                }
            }
            dtos.add(regularDto);

        }


        PageResult<RegularDto> regularDtoPageResult = new PageResult<>();
        regularDtoPageResult.setList(dtos);
        regularDtoPageResult.setTotalCount(pageResult.getTotalCount());
        regularDtoPageResult.setCurrPage(pageResult.getCurrPage());
        regularDtoPageResult.setPageSize(pageResult.getPageSize());
        regularDtoPageResult.setTotalPage(pageResult.getTotalPage());

        return R.ok(regularDtoPageResult);

    }
    @PostMapping("/updateRegular")
    @ApiOperation(value="修改新员工转正时间和状态")
    @SysAuthorityLog(value = "修改新员工转正时间和状态")
    @PreAuthorize("hasAuthority('emp:ygzz:update')")
    @Transactional
    public R updateRegular(@RequestBody UpdateRegularVo updateRegularVo, HttpServletRequest request) throws Exception{
        EmployeeInfoEntity entity = employeeInfoService.getByIdE(updateRegularVo.getOid());
        if(ObjectUtils.isEmpty(entity)){
            return  R.error("员工信息不存在，无法修改状态！");
        }
        //同一公司校验
        R checkR = loginController.checkOrgPermission(request,entity.getUnitId(),true);
        if(!R.isOk.equals(checkR.getStatus())){
            return checkR;
        }
        EmployeeInfoEntity employeeInfoEntity = BeanUtilsMabach.doToDto(updateRegularVo, EmployeeInfoEntity.class);
        employeeInfoEntity.setUpdateTime(new Date());
        Integer regularIsDone = 5;
        Date regularDay = updateRegularVo.getRegularDay();
        //预计转正日期为入职日期+试用期
        Integer probationday =3;
        if(!ObjectUtils.isEmpty(entity.getProbationday()))
             probationday =  entity.getProbationday();
        Date entityRegularDay = DateUtils.addDateMonths(entity.getHiredate(),probationday);
        if (regularDay!=null&&entityRegularDay!=null){
            Integer days = DateUtils.daysBetween(entityRegularDay, regularDay);
            if (days>=0){
                employeeInfoEntity.setIsRegular(2);
            }else {
                employeeInfoEntity.setIsRegular(4);
            }
        }

//        如果状态是不予转正，更新转正处理状态
        if(regularIsDone.equals(updateRegularVo.getDealStatus())){
            employeeInfoEntity.setRegularIsDone(1);
            employeeInfoEntity.setIsRegular(3);
        }
        EmployeeBpmEntity employeeBpmEntity = BeanUtilsMabach.doToDto(employeeInfoEntity, EmployeeBpmEntity.class);
        employeeBpmService.updateByIdE(employeeBpmEntity);
//        修改处理状态 1、评分审核中
//        employeeInfoEntity.setDealStatus(1);

        //修改招聘数据
        EmployeeInfoEntity entity1=employeeInfoService.getByIdE(employeeInfoEntity.getOid());
        if(!StringUtils.isEmpty(entity1.getRecruitmentId())){
            EmployeeRecruitmentEntity employeeRecruitmentEntity = BeanUtilsMabach.doToDto(employeeInfoEntity, EmployeeRecruitmentEntity.class);
            employeeRecruitmentEntity.setId(entity1.getRecruitmentId());
            employeeRecruitmentService.updateByIdE(employeeRecruitmentEntity);
        }

        return  employeeInfoService.updateByIdE(employeeInfoEntity);

    }



    @PostMapping("/getRegularBpmList")
    @ApiOperation("干部转正考察期追踪列表")
    @PreAuthorize("hasAuthority('emp:ygzz:get')")
    public R<PageResult<RegularBpmEntity>> getRegularBpmList(@RequestBody @Valid RegularListVo vo,HttpServletRequest request)throws  Exception{
        //获取当前用户角色下公司Id
        R checkR = loginController.checkOrgPermission(request,null,false);
        if(!R.isOk.equals(checkR.getStatus())){
            return checkR;
        }
        List<Long> orgIds = (List<Long>) checkR.getData();
        List<Long> orgId = null;
        List<Long> unitId = null;
        List<Long> jobId = null;
        if(!ObjectUtils.isEmpty(vo.getOrgname())){
            orgId = baseMssqlService.finOrgByOrgName(vo.getOrgname());
        }
        if(!ObjectUtils.isEmpty(vo.getBeforeUnitName())){
            unitId = baseMssqlService.finOrgByOrgName(vo.getBeforeUnitName());
        }
        if(!ObjectUtils.isEmpty(vo.getBeforeJobName())){
            jobId = baseMssqlService.findJobIdByJobName(vo.getBeforeJobName());
        }

        PageResult<RegularBpmEntity> result = regularBpmService.getRegularList(vo.getType(),vo.getStartTime(),vo.getName(),
                    vo.getCode(),vo.getEndTime(),vo.getOid(),false,orgIds,vo.getRegularBpmStatus(),
                    orgId,unitId,jobId,vo.getPageNum(),vo.getPageSize());
        List<RegularBpmEntity> resultList = result.getList();
        for (RegularBpmEntity regularBpmEntity : resultList) {
            setParam(regularBpmEntity); //封装基本信息
        }
        result.setList(resultList);
        return R.ok(result);
    }



    @PostMapping("/updateRegularDay")
    @ApiOperation("更新管理转正日期和状态")
    @PreAuthorize("hasAuthority('emp:ygzz:update')")
    @SysAuthorityLog(value = "修改干部转正时间和状态")
    @Transactional
    public R updateRegularDay(@RequestBody @Valid RegularDayVo vo){

        RegularBpmEntity regularBpmEntity = regularBpmService.getByIdE(vo.getId());
        if (ObjectUtils.isEmpty(regularBpmEntity)){
            return R.error("查询为空");
        }
        if(!regularBpmEntity.getRegularBpmStatus().equals(0)){
            return R.error("当前转正信息已发起BPM无法修改转正日期！");
        }
        regularBpmEntity.setRegularDay(vo.getEndRegularDay());
        Date endRegularDay = vo.getEndRegularDay();
        //预计转正日期为入职日期+试用期
        Date regularDay = DateUtils.addDateMonths(regularBpmEntity.getHiredate(),regularBpmEntity.getProbationday());
        if (endRegularDay!=null&&regularDay!=null){
            Integer days = DateUtils.daysBetween(regularDay, endRegularDay);
            if (days<=0){
                regularBpmEntity.setIsRegular(2);
            }else {
                regularBpmEntity.setIsRegular(4);
            }
        }

        Date date = new Date();
        int days = DateUtils.daysBetween(vo.getEndRegularDay(),date);
        if(days>=30){
            String title = "您的管理晋级考察即将结束请发起转正申请";
            R r = qwMsg.sendNoticeMsg("管理晋升转正",title, NoticeConst.MSG_TYPE_PROMOTION_REGULAR,false,regularBpmEntity.getOid(),regularBpmEntity.getId(),null,regularBpmEntity.getCode(),regularBpmEntity.getRegularDay(),null);
//            if(r.getFlag()){
                regularBpmEntity.setIsRegularRemind(1);
//            }
        }
        regularBpmService.updateByIdE(regularBpmEntity);
        return R.ok();
    }

    private void setParam(RegularBpmEntity regularBpmEntity) {
        Long orgId = regularBpmEntity.getOrgId();
        String orgNameById = jobController.getOrgNameById(orgId);
        regularBpmEntity.setOrgname(orgNameById);
        Long beforeOrgId = regularBpmEntity.getBeforeOrgId();
        String beforeOrgName = jobController.getOrgNameById(beforeOrgId);
        regularBpmEntity.setBeforeOrgName(beforeOrgName);
        Long unitId = regularBpmEntity.getUnitId();
        String unitName = jobController.getOrgNameById(unitId);
        regularBpmEntity.setUnitname(unitName);
        Long beforeUnitId = regularBpmEntity.getBeforeUnitId();
        String beforeUnitName = jobController.getOrgNameById(beforeUnitId);
        regularBpmEntity.setBeforeUnitName(beforeUnitName);
        Long jobId = regularBpmEntity.getJobId();
        String jobName = jobController.getJobName(jobId);
        regularBpmEntity.setJobname(jobName);
        Long beforeJobId = regularBpmEntity.getBeforeJobId();
        String beforeJobName = jobController.getJobName(beforeJobId);
        regularBpmEntity.setBeforeJobName(beforeJobName);
        Long jobLevelId = regularBpmEntity.getJobLevelId();
        String jobLevelNameById = jobController.getJobLevelNameById(jobLevelId);
        regularBpmEntity.setJobLevel(jobLevelNameById);
        Long beforeJobLevelId = regularBpmEntity.getBeforeJobLevelId();
        String beforeJobLevel = jobController.getJobLevelNameById(beforeJobLevelId);
        regularBpmEntity.setBeforeJobLevel(beforeJobLevel);
    }



}
